//
//  HSClassTableController.swift
//  HomeSchoolDemo
//
//  Created by 张晓林 on 16/9/30.
//  Copyright © 2016年 张晓林. All rights reserved.
//

import UIKit

class HSClassTableController: UIViewController {

    // 标签宽度高度
    let labelW: CGFloat = screenW / 8
    let labelH: CGFloat = 44
    // 全局的集合视图属性
    var collectionView: UICollectionView!
    // 数据源数组
    var dataArray: [HSClassTableModel] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        // 顶部导航条
        setupTopUI()
        // 集合视图
        addCollectionView()
        // 周视图
        setupWeekView()
        // 左边视图和线条
        setupLeftClassTimeView()
        // 数据请求
        loadData()
    }
    
    // 请求数据
    func loadData() {
        // 接口地址
        let url = "ZH-schoolname-S-curriculum"
        // 参数
        let key = userInfo["key"] as! String
        let param = ["key":key]
        // 请求数据
        HSNetworkTools.shared.downloadData(url: url, parameters: param) {[weak self] (data, err) in
            // 判断网络是否有问题
            guard let data = data as? NSDictionary else {
                print("网络异常")
                return
            }
            /// 判断返回的数据是否正常
            switch data["result"] as! Int {
            case 0:
                let dataArr = data["data"] as! NSArray
                // 循环获得每一天的字典
                for dict in dataArr {
                    let cDict = dict as? NSDictionary
                    // 先获得字典的keys，并按照小--大排序
                    let keys = (cDict?.allKeys as! [String]).sorted { $0 < $1 }
                    // 循环获得课程字典
                    for key in keys {
                        // 获得字典
                        let d = cDict?[key] as! [String: Any]
                        // 字典转模型
                        let model = HSClassTableModel(dict: d)
                        // 添加到数据源数组中
                        self?.dataArray.append(model)
                        // 添加空白对象
                        if key == "c4" {
                            self?.dataArray.append(HSClassTableModel(dict: [:]))
                        }
                    }
                }
                // 到这里就表示所有数据全部处理完成
                // 刷新视图
                self?.collectionView.reloadData()
            case 1:
                print("参数错误")
            default:
                break
            }
        }
    }
}

// MARK: - UI设置
extension HSClassTableController {
    // 顶部导航条
    func setupTopUI() {
        //模拟一个假导航栏
        let navVc = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 64))
        navVc.backgroundColor = UIColor().colorWithHex(0x009ee7)
        view.addSubview(navVc)
        //返回按钮
        let back = UIButton(frame: CGRect(x: 8, y: 16, width: 70, height: 48))
        back.setImage(UIImage(named:"返回按钮"), for: .normal)
        back.addTarget(self, action: #selector(backBtnClicked), for: .touchUpInside)
        navVc.addSubview(back)
        //文字
        let label = UILabel(frame: CGRect(x: 60, y: 16, width: 150, height: 48))
        label.text = "关于我们"
        label.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        label.font = UIFont.systemFont(ofSize: 20)
        
        navVc.addSubview(label)
    }
    
    // 周视图
    func setupWeekView() {
        // 创建周数组
        let weekTitle = ["","一","二","三","四","五","六","日"] as NSArray
        // 循环添加视图
        weekTitle.enumerateObjects({ (title, i, _) in
            // 初始化
            let label = UILabel(frame: CGRect(x: labelW*CGFloat(i), y: 64, width: labelW, height: labelH))
            label.text = title as? String
            label.textAlignment = .center
            label.font = UIFont.systemFont(ofSize: 13)
            label.textColor = UIColor().colorWithHex(0x00a0e9)
            view.addSubview(label)
        })
    }
    
    // 左边课时视图
    func setupLeftClassTimeView() {
        // 循环
        for i in 1..<10 {
            if i == 5 {
                let btn = UIButton(type: .custom)
                btn.frame = CGRect(x: 0,
                                   y: 65+labelH*CGFloat(i),
                                   width: screenW,
                                   height: labelH-1)
                btn.setBackgroundImage(UIImage(named:"curriculum_wuxiu_bg"),
                                       for: .normal)
                btn.setTitle("午 休", for: .normal)
                btn.isUserInteractionEnabled = false
                btn.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
                view.addSubview(btn)
                
            }else {
                let label = UILabel(frame: CGRect(x: 0,
                                                  y: 64+labelH*CGFloat(i),
                                                  width: labelW,
                                                  height: labelH))
                if i > 5 {
                    label.text = "\(i-1)"
                }else {
                    label.text = "\(i)"
                }
                label.textAlignment = .center
                label.font = UIFont.systemFont(ofSize: 13)
                label.textColor = UIColor().colorWithHex(0x00a0e9)
                view.addSubview(label)
            }
            // 添加线条
            let lineV = UIView(frame: CGRect(x: 8,
                                             y: 64+labelH*CGFloat(i+1),
                                             width: screenW-16,
                                             height: 1))
            
            lineV.backgroundColor = UIColor().colorWithHex(0x00a0e9)
            view.addSubview(lineV)
        }
    }
    
    // 中间集合视图
    func addCollectionView() {
        // 设置布局对象
        let flowLayout = UICollectionViewFlowLayout()
        // 设置大小和间距
        flowLayout.itemSize = CGSize(width: labelW,
                                     height: labelH)
        
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 0
        // 滚动方向
        flowLayout.scrollDirection = .horizontal
        
        let rect = CGRect(x: labelW,
                          y: labelH+64,
                          width: labelW*7,
                          height: labelH*9)
        
        collectionView = UICollectionView(frame: rect, collectionViewLayout: flowLayout)
        collectionView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        // 设置代理和数据源
        collectionView.dataSource = self
        // 注册原形cell
        collectionView.register(HSClassTableCell.self, forCellWithReuseIdentifier: "classTableCell")
        
        view.addSubview(collectionView)
    }
    
    // 返回方法
    func backBtnClicked() {
        dismiss(animated: true, completion: nil)
    }
}

// MARK: - 集合视图的数据源方法
extension HSClassTableController: UICollectionViewDataSource {
    // 格子数量
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    // 格子视图
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        // 缓存获取
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "classTableCell", for: indexPath) as? HSClassTableCell
        // 赋值
        cell?.titleL?.text = dataArray[indexPath.item].courseName
        
        return cell!
    }
}















